package com.gxan.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxan.common.R;
import com.gxan.service.UserService;
import com.gxan.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端输入的验证码，先校验验证码是否正确才去校正账号密码
        String vercode = request.getParameter("vercode");
        String verificationCode = (String)request.getSession().getAttribute("verificationCode");
        R<Object> objectR = new R<Object>();
        if(vercode==null||vercode==""||!vercode.equalsIgnoreCase(verificationCode)){
            //验证码不匹配,传回数据
            objectR.setCode(401);
            objectR.setMsg("验证码出错");
        }else{
            //验证码正确，验证账号密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //传递给service进行逻辑处理
            UserService service = new UserServiceImpl();
            objectR = service.login(username, password);
            if(objectR.getData()==null){
                //如果账号密码错误，验证码必须重新输入
                request.getSession().removeAttribute("verificationCode");
                // request.getRequestDispatcher("/captcha").forward(request,response);
            }

        }
        //前端需要的数据，状态码，状态信息可能是登录成功也可能是失败，数据
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(objectR));
        response.getWriter().close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
